package com.budwk.app.sqfwV2.service.meeting;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.Asserts;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.SqfwServicerecordService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplateExcelCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwV2.dto.MeetingParamDTO;
import com.budwk.app.sqfwV2.enums.MeetingEnums;
import com.budwk.app.sqfwV2.generator.meeting.MeetingExcelGenerator;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@IocBean
public class MeetingExcelService extends SqfwTemplateExcelCommonService {

    private final Map<String, Integer> mapFileIndex = new ConcurrentHashMap<>();
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;


    /**
     * 允许自定义生成excel的原材料，
     *
     * @param baseExcelParam 生成excel提供的原材料
     * @param userId         用户id
     * @param sqfwIdList     社区服务id列表
     */
    @Override
    protected void customerPopularBaseExcelParam(BaseExcelParamDTO baseExcelParam, String userId, List<String> sqfwIdList) {
        if (!sqfwIdList.isEmpty()) {
            String sqfwId = sqfwIdList.get(0);
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
            if (null != serviceRecord) {
                baseExcelParam.setProvince(serviceRecord.getProvince());
                baseExcelParam.setCity(serviceRecord.getCity());
                baseExcelParam.setDistrict(serviceRecord.getDistrict());
                baseExcelParam.setCounty(serviceRecord.getCounty());
                baseExcelParam.setCommunity(serviceRecord.getCommunity());
            }
        }

    }

    @Override
    protected void customerPopularBaseExcelParamForAdmin(BaseExcelParamDTO baseExcelParam, String userId, List<String> formSummaryNewIdList) {

    }

    @Override
    protected List<ExcelGeneratorConfig> getExcelCodeGeneratorConfig(List<ExcelCreateConfig> excelConfigList, BaseExcelParamDTO baseExcelParam) {
        List<ExcelGeneratorConfig> generatorList = Lists.newArrayList();
        ExcelGeneratorConfig excelConfig = new ExcelGeneratorConfig();
        excelConfig.setGenerator(new MeetingExcelGenerator(MeetingEnums.getTemplatePath(Integer.valueOf(excelConfigList.get(0).getFileIdentity()))));
        excelConfig.setExcelCreateConfig(excelConfigList.get(0));
        generatorList.add(excelConfig);
        return generatorList;
    }


    /**
     * 选择使用哪一个excel生成器来生成excel，默认一个Excel会对应一个Generator
     *
     * @return 结果
     */

    @Override
    protected AbstractCustomerPdfCreateField parseParamData(String paramDataStr) {
        return JSONObject.parseObject(paramDataStr, MeetingParamDTO.class);
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    protected String getSqfwFormSummaryType() {
        return SupportBusinessTypeEnum.MEETING_ACTIVITY_VISIT_RECORD.getCode();
    }

    public List<GenerateExcelUrlVO> generateExcel(Integer templateCode, boolean isTemplate, String userId, String sqwfIdList, boolean isAdmin) {
        if (StringUtils.isBlank(sqwfIdList)) return Lists.newArrayList();
        List<ExcelCreateConfig> excelCreateConfigs = Lists.newArrayList();
        ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
        excelCreateConfig.setFileIdentity(String.valueOf(templateCode));
        excelCreateConfig.setOnlyGenerateTemplateFlag(isTemplate);
        excelCreateConfigs.add(excelCreateConfig);
        if (isTemplate) {
            //下载模板
            return downLoadTemplate(templateCode);
        }
        String key;
        if (isAdmin) {
            key="admin_"+userId;
            mapFileIndex.put(key, templateCode);
            //后台web导出入口
            return super.generateExcelForAdmin(excelCreateConfigs, userId, Lists.newArrayList(sqwfIdList.split(",")));
        }else{
            key = "app_"+userId;
            mapFileIndex.put(key, templateCode);
            return super.generateExcel(excelCreateConfigs, userId, Lists.newArrayList(sqwfIdList.split(",")));
        }
    }

    private List<GenerateExcelUrlVO> downLoadTemplate(Integer fileIndex) {
        MeetingEnums meetingEnums = MeetingEnums.getTemplatEnums(fileIndex);
        String downLoadFile = null;
        if (null != meetingEnums) {
            if (MeetingEnums.MEETING_MINUTES_EXCEL.getCode() == meetingEnums.getCode()) {
                downLoadFile = DownLoadFileNameEnum.MEETING_MINUTES_EXCEL.getName();
            } else if (MeetingEnums.MEETING_MINUTES_DETAIL_EXCEL.getCode() == meetingEnums.getCode()) {
                downLoadFile = DownLoadFileNameEnum.MEETING_MINUTES_DETAIL_EXCEL.getName();
            } else if (MeetingEnums.VISITING_RECORDS_EXCEL.getCode() == meetingEnums.getCode()) {
                downLoadFile = DownLoadFileNameEnum.MEETING_VISITING_RECORDS_EXCEL.getName();
            } else if (MeetingEnums.ACTIVITIES_EXCEL.getCode() == meetingEnums.getCode()) {
                downLoadFile = DownLoadFileNameEnum.MEETING_ACTIVITIES_EXCEL.getName();
            }
        }
        String templatePath = CommonFormOfficeUtils.getTemplatePathByOS(meetingEnums.getTemplat());
        String fileName = downLoadFile + DateUtil.format(new Date(), "yyyyMMddHHmmss");
        ExcelFileCreateParamBO excelFileCreateParam = new ExcelFileCreateParamBO();
        excelFileCreateParam.setTemplatePath(templatePath);
        excelFileCreateParam.setSheetParam(new HashMap<>());
        excelFileCreateParam.setDataList(null);
        excelFileCreateParam.setClazz(null);
        excelFileCreateParam.setFileName(fileName);
        String excelAndUpload = CommonFormOfficeUtils.createExcelAndUpload(excelFileCreateParam);
        List<GenerateExcelUrlVO> excelUrlVOList = Lists.newArrayList();
        GenerateExcelUrlVO excelUrlVO = new GenerateExcelUrlVO();
        if (StringUtils.isNotBlank(excelAndUpload)) {
            excelUrlVO.setExcelUrl(excelAndUpload);
            excelUrlVO.setCreateConditionFlag(true);
        } else {
            excelUrlVO.setCreateConditionFlag(false);
        }
        excelUrlVOList.add(excelUrlVO);
        return excelUrlVOList;
    }

    protected List<Sqfw_formSummary_new> queryForSummaryDataForAdmin(List<String> sqfwIdList) {
        String sqfwFormSummaryType = getSqfwFormSummaryType();
        if (StringUtils.isBlank(sqfwFormSummaryType)) Asserts.fail("forSummary类型不能为空");
        String userId = SecurityUtil.getUserId();
        String key = "admin_"+userId;
        Integer fileIndex = mapFileIndex.get(key);
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getId, "in", sqfwIdList).and("type", "=", sqfwFormSummaryType);
        if (!ObjectUtil.isEmpty(fileIndex)) {
            cnd.and("param_data ->> 'type'", "in", String.format("'%s'", MeetingEnums.getTemplatEnums(fileIndex).getName().split("_")[0]));
        } else {
            log.info("MeetingExcelService.queryForSummaryDataForAdmin未找到文件索引！");
            return Lists.newArrayList();
        }
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = sqfwFormsummaryNewService.query(cnd);
        mapFileIndex.remove(key);
        return sqfwFormSummaryNewList;
    }

    protected List<Sqfw_formSummary_new> queryForSummaryData(List<String> sqfwIdList,Map<String,Object> param) {
        String sqfwFormSummaryType = getSqfwFormSummaryType();
        if (StringUtils.isBlank(sqfwFormSummaryType)) Asserts.fail("forSummary类型不能为空");
        String userId = SecurityUtil.getUserId();
        String key = "app_"+userId;
        Integer fileIndex = mapFileIndex.get(key);
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getSqfwId, "in", sqfwIdList).and("type", "=", sqfwFormSummaryType);
        if (!ObjectUtil.isEmpty(fileIndex)) {
            cnd.and("param_data ->> 'type'", "in", String.format("'%s'", MeetingEnums.getTemplatEnums(fileIndex).getName().split("_")[0]));
        } else {
            log.info("MeetingExcelService.queryForSummaryData未找到文件索引！");
            return Lists.newArrayList();
        }
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = sqfwFormsummaryNewService.query(cnd);
        mapFileIndex.remove(key);
        return sqfwFormSummaryNewList;
    }
}
